import uniPopup from '@/components/uni-popup/uni-popup.vue' // 弹出框组件
import userAgreementPopup from '@/components/pages-login/user-agreement-popup/user-agreement-popup.vue' //免责
import md5 from '@/utils/blueimp-md5.js'

export default {
  data() {
    return {
      namePlaceholder: '企业名称', //input默认提示
      passwordPlaceholder: '请设置密码',
      againpasswordPlaceholder: '请确认密码',
      showNamePlaceholder: false, //企业名称小标题
      showpasswordPlaceholder: false, //密码小标题
      againshowpasswordPlaceholder: false, //确认密码小标题
      showNameClearIcon: false, //企业名称小叉叉
      showPasswordClearIcon: false, //密码小叉叉
      againshowPasswordClearIcon: false, //确认密码小叉叉
      isDisabled: true,
      company: '', //企业名称
      Password: '', //密码
      surepassword: '', // (string): 确认密码
      showPassword: true, //隐藏显示密码
      eye: 'eye-off', //显示隐藏的眼睛图标
      againshowPassword: true, //隐藏显示确认密码
      againeye: 'eye-off', //显示隐藏确认密码的眼睛图标
      showComany: false, //企业联想列表
      searchkey: '', // 搜索关键字
      state: '', //是否有该公司
      qcclist: [], //企查查的公司列表
      list: [], //数据库的公司列表
      pageindex: '', //公司的当前页
      showLine: true, //切换显示密码html
      qccPageIndex: 1,
      yzcPageIndex: 1,
      hasNotchInScreen: false, //是否为刘海屏
      type: 'new', //创建企业类型 add 添加  new 注册
      isJoinCompany: false, //是否为加入公司
      isUserIdentity: false, //是否已完成个人信息认证
      isDeparture: false, //是否离职重新加入
      phone: '', //电话
      choosePage: false,
      popshow: false, //加入公司通知
      isBack: true, //是否能返回
    }
  },
  computed: {
    listHeight() {
      let qccHeight = 80,
        yzcHeight = 80
      if (this.qcclist.length) {
        qccHeight = Math.min(this.qcclist.length, 4) * 80
      }
      if (this.list.length) {
        yzcHeight = Math.min(this.list.length, 4) * 80
      }
      return {
        qccHeight,
        yzcHeight,
      }
    },
  },
  //监听默认返回事件
  onBackPress(e) {
    if (this.type === 'new') {
      // if(this.isBack){
      uni.reLaunch({
        url: '/pages_login/login/login',
      })
      // }
      return true
    } else {
      // if(this.isBack){
      uni.switchTab({
        url: '/pages/me/me'
      })
      // }
      return true

    }
  },

  onLoad(e) {
    this.choosePage = this.$store.state.userInfoDetail.user.isPWD
    console.log(e)
    this.phone = e.phone
    this.IsCurrentUserIdentityAndDeparture()
    // #ifdef APP-PLUS
    this.hasNotchInScreen = plus.navigator.hasNotchInScreen()
    // #endif
    this.type = e.type ? e.type : 'new'
    // 添加企业不需要设置密码
    if (this.type === 'add') {
      uni.setNavigationBarTitle({
        title: '创建企业',
      })
      this.showLine = false
    }

    this.showLine = !this.choosePage
    // console.log(this.showLine)
    // this.isCurrentUserIdentity()
    console.log(this.$store.state)
    this.Password = this.$store.state.user.registerInfo.psd
    this.searchkey = this.$store.state.user.registerInfo.name
    // console.log(this.searchkey)
    if (this.Password) {
      this.showPasswordClearIcon = true
    }
    if (this.searchkey) {
      this.showNameClearIcon = true
      this.qccvaguesearchCompany('search')
      this.checkCompanyIsExist(this.searchkey, 'new', 1)

    }

  },

  methods: {
    md5,
    //个人认证状态查询
    isCurrentUserIdentity() {
      this.$api.user
        .isCurrentUserIdentity()
        .then(res => {
          this.isUserIdentity = res.data

        })
        .catch(e => {
          console.log(e)
        })
    },
    //个人认证状态查询
    IsCurrentUserIdentityAndDeparture() {
      this.$api.user
        .IsCurrentUserIdentityAndDeparture()
        .then(res => {
          console.log(res)
          this.isUserIdentity = res.data.isAuth //是否认证身份信息
          this.isDeparture = res.data.isDeparture //是否离职
        })
        .catch(e => {
          console.log(e)
        })
    },

    //点击input后面的小叉叉显示隐藏
    clearIcon(e) {
      this[e] = ''
      if (e === 'searchkey') {
        this.showNameClearIcon = false
        this.namePlaceholder = '企业名称' //input默认提示
        this.showNamePlaceholder = false
        this.isDisabled = true
      } else if (e === 'Password') {
        this.showPasswordClearIcon = false
        this.passwordPlaceholder = '请设置密码' //input默认提示
        this.showpasswordPlaceholder = false
      } else {
        this.againshowPasswordClearIcon = false
        this.againpasswordPlaceholder = '请确认密码' //input默认提示
        this.againshowpasswordPlaceholder = false
      }
    },
    //实时监控 企业名称input输入的值
    clearInput0(event) {
      if (event.detail.value !== this.company) {
        this.isDisabled = true
      }
      this.company = event.detail.value //input输入的内容
      if (event.detail.value.length > 0) {
        this.showNameClearIcon = true //小叉叉
        this.showComany = true
        this.qccvaguesearchCompany('search') //企查查搜索公司名称
        this.SearchCompany('search') //数据库搜索公司名称
      } else {
        this.showNameClearIcon = false //小叉叉
      }
    },
    //实时监控 请设置密码input输入的值
    clearInput1(event) {
      this.Password = event.detail.value //input输入的内容
      if (event.detail.value.length > 0) {
        this.showPasswordClearIcon = true //小叉叉
      } else {
        this.showPasswordClearIcon = false //小叉叉
      }
    },
    //实时监控 请确认密码input输入的值
    clearInput2(event) {
      this.surepassword = event.detail.value //input输入的内容
      if (event.detail.value.length > 0) {
        this.againshowPasswordClearIcon = true //小叉叉
      } else {
        this.againshowPasswordClearIcon = false //小叉叉
      }
    },

    //当input框获取焦点的时候，显示小标题，隐藏默认提示文字
    toggleSmalltitle(type, isshow) {
      // console.log(type, isshow)

      //type 0 企业名称 1请设置密码 2确认密码 isshow 0获取焦点 1失去焦点
      // const reg = /(?=.*([`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、].*))(?=.*([0-9a-zA-Z].*))[A-Za-z\d`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]{6,20}$/
      if (type === 0) {
        //0 企业名称
        if (isshow === 0) {

          // console.log(11111)
          // 企业名称获取焦点
          this.namePlaceholder = ''
          this.showNamePlaceholder = true
          if (this.company.length > 0) {
            this.showNameClearIcon = true //小叉叉
            this.showComany = true
            this.qccvaguesearchCompany('search') //企查查搜索公司名称
            this.SearchCompany('search') //数据库搜索公司名称
          }

        } else {
          // 企业名称失去焦点
          if (this.company === '') {
            this.namePlaceholder = '企业名称' //input默认提示
            this.showNamePlaceholder = false
          } else {
            this.showNamePlaceholder = true
          }
          // #ifdef APP-PLUS
          this.showComany = false
          // #endif

          // #ifndef APP-PLUS
          setTimeout(() => {
            this.showComany = false
          }, 500)
          // #endif
        }
      } else if (type === 1) {
        //1请设置密码
        if (isshow === 0) {
          // 请设置密码获取焦点
          this.passwordPlaceholder = ''
          this.showpasswordPlaceholder = true
        } else {
          // 请设置密码失去焦点
          if (this.Password === '') {
            this.passwordPlaceholder = '请设置密码' //input默认提示
            this.showpasswordPlaceholder = false
            this.showPasswordClearIcon = false //隐藏小叉叉 和眼睛
          } else {
            // if (!reg.test(this.Password)) {
            //   uni.showToast({
            //     title: '密码须由6-20位字母、数字加符号组成',
            //     icon: 'none',
            //   })
            // }
            if (this.Password.length < 6) {
              uni.showToast({
                title: '密码为6-20位',
                icon: 'none',
              })
            }
            // else if(this.surepassword && this.surepassword !== this.Password){
            //         uni.showToast({
            // 	  title: '两次输入的密码不一致',
            // 	  icon: 'none'
            //         })
            //       }
            this.showpasswordPlaceholder = true
          }
        }
      } else {
        //确认密码
        if (isshow === 0) {
          // 请设置密码获取焦点
          this.againpasswordPlaceholder = ''
          this.againshowpasswordPlaceholder = true
        } else {
          // 请设置密码失去焦点
          if (this.surepassword === '') {
            this.againshowPasswordClearIcon = false //隐藏小叉叉 和眼睛
            this.againpasswordPlaceholder = '请确认密码' //input默认提示
            this.againshowpasswordPlaceholder = false
          } else {
            if (!reg.test(this.surepassword)) {
              uni.showToast({
                title: '密码须由6-20位',
                icon: 'none',
              })
            } else if (this.Password && this.surepassword !== this.Password) {
              uni.showToast({
                title: '两次输入的密码不一致',
                icon: 'none',
              })
            }
            this.showpasswordPlaceholder = true
          }
        }
      }
      uni.hideLoading()
    },
    //切换密码的显示隐藏
    changePassword(type) {
      //type 0设置密码 1确认密码
      if (type === 0) {
        if (this.eye === 'eye-off') {
          this.eye = 'eye-fill'
        } else {
          this.eye = 'eye-off'
        }
        this.showPassword = !this.showPassword
      } else {
        if (this.againeye === 'eye-off') {
          this.againeye = 'eye-fill'
        } else {
          this.againeye = 'eye-off'
        }
        this.againshowPassword = !this.againshowPassword
      }
    },
    //数据库搜索公司名称
    async SearchCompany(type) {
      if (!this.searchkey) return false
      this.yzcPageIndex = type === 'search' ? 1 : ++this.yzcPageIndex
      try {
        const result = await this.$api.user.registedSearch({
          PageIndex: this.yzcPageIndex,
          PageSize: 10,
          searchkey: this.searchkey,
        })
        if (result.data.list && result.data.list.length > 0) {
          if (this.yzcPageIndex === 1) {
            this.list = result.data.list
          } else {
            this.list = this.list.concat(result.data.list)
          }
        }
        // uni.hideLoading()
      } catch (e) {
        // uni.hideLoading()
        //TODO handle the exception
      }
    },
    //企查查搜索公司名称
    async qccvaguesearchCompany(type) {

      this.qccPageIndex = type === 'search' ? 1 : ++this.qccPageIndex

      try {
        const res = await this.$api.user.qccSearch({
          paramStr: this.searchkey,
          provinceCode: '',
          cityCode: '',
          pageSize: 10,
          pageIndex: this.qccPageIndex,
        })
        if (res.data.result && res.data.result.length > 0) {
          if (this.qccPageIndex === 1) {
            this.qcclist = res.data.result
          } else {
            this.qcclist = this.qcclist.concat(res.data.result)
          }
        }
        // uni.hideLoading()
        uni.hideNavigationBarLoading() //关闭加载动画
      } catch (e) {
        // uni.hideLoading()
        //TODO handle the exception
      }
    },
    //点击搜索的公司名称
    goAuthenticationPage(name, isJoin) {
      this.searchkey = name
      this.showComany = false
      // this.$store.commit('user/setCompanyInfo', {
      //   name,
      //   isJoinCompany: isJoin,
      // })
      this.checkCompanyIsExist(name, 'new', 1) //检查数据库中是否有该公司
    },

    // 完成提交-设置密码
    async setPassword() {
      // debugger
      if (this.isDisabled) {
        if (!this.qcclist.length) {
          uni.showToast({
            title: '请选择企业名称',
            icon: 'none',
          })
          return
        } else {
          this.searchkey = this.qcclist[0].name
          this.showComany = false
          try {
            const res = await this.$api.user.companyIsExist({
              company: this.qcclist[0].name,
              check: 2
            })
            this.$store.commit('user/setCompanyInfo', {
              name: this.qcclist[0].name,
              isJoinCompany: res.data,
            })

            this.isJoinCompany = res.data
            this.isDisabled = false
            this.dataCheck()
          } catch (e) {
            console.log(e)
            //TODO handle the exception
          }
        }
      } else {
        this.dataCheck()
      }
    },

    async dataCheck() {
      if (this.Password) {
        // const reg = /(?=.*([`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、].*))(?=.*([0-9a-zA-Z].*))[A-Za-z\d`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]{6,20}$/
        // if (!reg.test(this.Password)) {
        //   uni.showToast({
        //     title: '密码须由6-20位字母、数字加符号组成',
        //     icon: 'none',
        //   })
        //   return
        // }
        if (this.Password.length < 6) {
          uni.showToast({
            title: '密码为6-20位',
            icon: 'none',
          })
          return
        }
        try {
          const res = await this.$api.user.register({
            password: this.md5(this.Password),
          })

          this.gotoPage()
          this.$store.commit('user/setRegisterInfo', {
            name: this.searchkey,
            psd: this.Password
          })
        } catch (e) {
          //TODO handle the exception
        }
      } else {
        this.gotoPage()
      }
    },

    gotoPage() {
      if (this.type === 'new') {
        //新用户注册
        if (this.isUserIdentity) {
          //已做个人认证
          if (this.isJoinCompany) {
            // console.log(this.searchkey, 'join')
            this.checkCompanyIsExist(this.searchkey, 'join', 2).then(res => {
              console.log(res)
              if (res) {
                this.popshow = true
                // if (res.code === 200) {
                let joinData = {
                  mobile: this.phone,
                  companyName: this.searchkey,
                }

                this.$api.user.ApplyJoin(joinData)
                // }
              }

            })

            this.isBack = false
            // this.$refs.popup.open()

          } else {
            uni.redirectTo({
              url: '/pages_login/authenticationCompany/authenticationCompany?type=new&companyName=' +
								this.searchkey,
            })
          }
        } else {
          //未进行个人认证
          uni.redirectTo({
            url: '/pages_login/authenticationPersonal/authenticationPersonal?companyName=' +
							this.searchkey + '&phone=' + this.phone,
          })
        }
      } else {
        this.checkCompanyIsExist(this.searchkey, 'join', 2)
        //老用户添加企业
        if (this.isJoinCompany) {
          this.popshow = true
          this.isBack = false
          //    uni.navigateTo({
          //      url: '/pages_login/authenticationState/authenticationState?type=add&state=0&companyName=' +
          // this.searchkey + '&phone=' + this.phone,
          //    })
        } else {
          uni.redirectTo({
            url: '/pages_login/authenticationCompany/authenticationCompany?type=add&companyName=' +
							this.searchkey + '&phone=' + this.phone,
          })
        }
      }
    },
    closePopup() {
      // 等待审核
      this.popshow = false
      this.isBack = true
      uni.navigateTo({
        url: '/pages_login/authenticationState/authenticationState?type=add&state=0&companyName=' +
					this.searchkey + '&phone=' + this.phone,
      })
    },
    //检查数据库是否有该公司
    async checkCompanyIsExist(name, type, check) {
      uni.showLoading({
        title: ''
      })
      console.log(name)
      try {
        const res = await this.$api.user.companyIsExist({
          company: name,
          check: check
        })

        if (type === 'new') {
          this.$store.commit('user/setCompanyInfo', {
            name,
            isJoinCompany: res.data,
          })
          this.isJoinCompany = res.data
          this.isDisabled = false
        } else {
          console.log('加入公司', res)
        }
        uni.hideLoading()
        return true
      } catch (e) {
        console.log(e)
        if (e.code) {
          this.popshow = false
          return false
        }
        uni.hideLoading()
        //TODO handle the exception
      }
    },
  },
}
